<template>
	<a-row :gutter="10">
		<a-col :xs="24" :sm="24" :md="24" :lg="4" :xl="4">
			<a-card :bordered="false" :loading="cardLoading">
				<a-tree
					v-if="treeData.length > 0"
					v-model:expandedKeys="defaultExpandedKeys"
					:tree-data="treeData"
					:field-names="treeFieldNames"
					@select="treeSelect"
				>
				</a-tree>
				<a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" />
			</a-card>
		</a-col>
		<a-col :xs="24" :sm="24" :md="24" :lg="20" :xl="20">
			<a-card :bordered="false">
				<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
					<a-row :gutter="24">
						<a-col :span="6">
							<a-form-item label="商品编码" name="productionCode">
								<a-input v-model:value="searchFormState.productionCode" placeholder="请输入商品编码" />
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="主条码" name="productionBarcode">
								<a-input v-model:value="searchFormState.productionBarcode" placeholder="请输入主条码" />
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="商品名称" name="productionName">
								<a-input v-model:value="searchFormState.productionName" placeholder="请输入商品名称" />
							</a-form-item>
						</a-col>
						<a-col :span="6" v-show="advanced">
							<a-form-item label="拼音码" name="productionPinyincode">
								<a-input v-model:value="searchFormState.productionPinyincode" placeholder="请输入拼音码" />
							</a-form-item>
						</a-col>
						<a-col :span="6" v-show="advanced">
							<a-form-item label="品牌" name="productionBrand">
								<xn-page-select
									ref="xnproductionBrandPageSelectRef"
									v-model:value="searchFormState.productionBrand"
									placeholder="请选择品牌"
									allow-clear
									show-search
									:page-function="productionBrandSelector"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6" v-show="advanced">
							<a-form-item label="商品分类" name="productionCategoriesId">
								<a-input v-model:value="searchFormState.productionCategoriesId" placeholder="请输入商品分类" />
							</a-form-item>
						</a-col>
						<a-col :span="6" v-show="advanced">
							<a-form-item label="主供应商" name="productionSupplierMain">
								<xn-page-select
									ref="xnproductionSupplierMainPageSelectRef"
									v-model:value="searchFormState.productionSupplierMain"
									placeholder="请选择主供应商"
									allow-clear
									show-search
									:page-function="productionSupplierMainSelector"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6" v-show="advanced">
							<a-form-item label="供应商列表" name="productionSupplierList">
								<xn-page-select
									ref="xnproductionSupplierListPageSelectRef"
									v-model:value="searchFormState.productionSupplierList"
									placeholder="请选择供应商列表"
									allow-clear
									show-search
									:page-function="productionSupplierListSelector"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6" v-show="advanced">
							<a-form-item label="商品标签" name="productionTag">
								<a-input v-model:value="searchFormState.productionTag" placeholder="请输入商品标签" />
							</a-form-item>
						</a-col>
						<a-col :span="6" v-show="advanced">
							<a-form-item label="商品状态" name="productionStatus">
								<a-select v-model:value="searchFormState.productionStatus" placeholder="请选择商品状态" :options="productionStatusOptions" allow-clear/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-button type="primary" @click="tableRef.refresh()">查询</a-button>
							<a-button style="margin: 0 8px" @click="reset">重置</a-button>
							<a @click="toggleAdvanced" style="margin-left: 8px">
								{{ advanced ? '收起' : '展开' }}
								<component :is="advanced ? 'up-outlined' : 'down-outlined'"/>
							</a>
						</a-col>
					</a-row>
				</a-form>
				<s-table
					ref="tableRef"
					:columns="columns"
					:data="loadData"
					:alert="options.alert.show"
					bordered
					:row-key="(record) => record.id"
					:tool-config="toolConfig"
					:row-selection="options.rowSelection"
				>
					<template #operator class="table-operator">
						<a-space>
							<a-button type="primary" @click="formRef.onOpen(null,searchFormState.productionCategoriesId)" v-if="hasPerm('supplierBaseProductionsAdd')">
								<template #icon><plus-outlined /></template>
								新增
							</a-button>
							<xn-batch-delete
								v-if="hasPerm('supplierBaseProductionsBatchDelete')"
								:selectedRowKeys="selectedRowKeys"
								@batchDelete="deleteBatchSupplierProductions"
							/>
						</a-space>
					</template>
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'productionImages'">
							<div v-if="record.productionImages">
								<a-image :src="record.productionImages" style="width: 30px; height: 30px" />
							</div>
							<span v-else>未上传</span>
						</template>
						<template v-if="column.dataIndex === 'productionIsstock'">
							{{ $TOOL.dictTypeData('COMMON_SWITCH', record.productionIsstock) }}
						</template>
						<template v-if="column.dataIndex === 'productionStatus'">
							{{ $TOOL.dictTypeData('COMMON_STATUS', record.productionStatus) }}
						</template>
						<template v-if="column.dataIndex === 'productionHasextbarcode'">
							{{ $TOOL.dictTypeData('COMMON_STATUS', record.productionHasextbarcode) }}
						</template>
						<template v-if="column.dataIndex === 'action'">
							<a-space>
								<a @click="formRef.onOpen(record)" v-if="hasPerm('supplierBaseProductionsEdit')">编辑</a>
								<a-divider type="vertical" v-if="hasPerm(['supplierBaseProductionsEdit', 'supplierBaseProductionsDelete'], 'and')" />
								<a-popconfirm title="确定要删除吗？" @confirm="deleteSupplierProductions(record)">
									<a-button type="link" danger size="small" v-if="hasPerm('supplierBaseProductionsDelete')">删除</a-button>
								</a-popconfirm>
							</a-space>
						</template>
					</template>
				</s-table>
			</a-card>
		</a-col>
	</a-row>

	<Form ref="formRef" @successful="tableRef.refresh()" />
</template>

<script setup name="supplierBaseProductions">
	import tool from '@/utils/tool'
	import { cloneDeep } from 'lodash-es'
	import Form from './form.vue'
	import { isEmpty } from 'lodash-es'
	import supplierProductionsApi from '@/api/supplier/base/supplierProductionsApi'
	import supplierBrandsApi from "@/api/supplier/base/supplierBrandsApi";
	import supplierSuppliersApi from "@/api/supplier/purchase/supplierSuppliersApi";
	import {Empty} from "ant-design-vue";
	import supplierCategoriesApi from "@/api/supplier/base/supplierCategoriesApi";
	import supplierObjectsApi from "@/api/supplier/custom/supplierObjectsApi";
	const searchFormState = ref({})
	const searchFormRef = ref()
	const tableRef = ref()
	const formRef = ref()
	// 默认展开的节点
	const defaultExpandedKeys = ref([])
	const treeData = ref([])
	// 替换treeNode 中 title,key,children
	const treeFieldNames = { children: 'children', title: 'name', key: 'id' }
	const cardLoading = ref(true)
	// 加载左侧的树
	const loadTreeData = () => {
		supplierCategoriesApi
			.categoriesTree()
			.then((res) => {
				cardLoading.value = false
				if (res !== null) {
					treeData.value = [
						{
							id: '',
							parentId: '0',
							name: '全部分类',
							children: res
						}
					]
					// treeData.value = res
					console.log(treeData.value)
					if (isEmpty(defaultExpandedKeys.value)) {
						// 默认展开2级
						treeData.value.forEach((item) => {
							// 因为0的顶级
							if (item.parentId === '0') {
								defaultExpandedKeys.value.push(item.id)
								// 取到下级ID
								if (item.children) {
									item.children.forEach((items) => {
										defaultExpandedKeys.value.push(items.id)
									})
								}
							}
						})
					}
				}
			})
			.finally(() => {
				cardLoading.value = false
			})
	}
	// 点击树查询
	const treeSelect = (selectedKeys) => {
		if (selectedKeys.length > 0) {
			searchFormState.value.productionCategoriesId = selectedKeys.toString()
		} else {
			delete searchFormState.value.productionCategoriesId
		}
		console.log(searchFormState.value)
		tableRef.value.refresh(true)
	}
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	// 查询区域显示更多控制
	const advanced = ref(false)
	const toggleAdvanced = () => {
		advanced.value = !advanced.value
	}
	const columns = [
		{
			title: '商品编码',
			dataIndex: 'productionCode'
		},
		{
			title: '主条码',
			dataIndex: 'productionBarcode'
		},
		{
			title: '商品名称',
			dataIndex: 'productionName'
		},
		{
			title: '品牌',
			dataIndex: 'productionBrand'
		},
		{
			title: '商品图片',
			dataIndex: 'productionImages',
			checked: false
		},
		{
			title: '商品分类',
			dataIndex: 'productionCategoriesIdName'
		},
		{
			title: '规格',
			dataIndex: 'productionSpec'
		},
		{
			title: '产地',
			dataIndex: 'productionOrigin',
			checked: false
		},
		{
			title: '单位',
			dataIndex: 'productionUnit'
		},
		{
			title: '采购单价',
			dataIndex: 'productionPriceProcure'
		},
		{
			title: '最近采购单价',
			dataIndex: 'productionPriceProcureLast',
			checked: false
		},
		{
			title: '销售单价',
			dataIndex: 'productionPriceSale'
		},
		{
			title: '批发单价',
			dataIndex: 'productionPriceWhole'
		},
		{
			title: '最低销售单价',
			dataIndex: 'productionPriceLimit',
			checked: false
		},
		{
			title: '是否计库存',
			dataIndex: 'productionIsstock',
			checked: false
		},
		{
			title: '库存',
			dataIndex: 'productionStock'
		},
		{
			title: '库存上限',
			dataIndex: 'productionStockUp',
			checked: false
		},
		{
			title: '库存下限',
			dataIndex: 'productionStockLow',
			checked: false
		},
		{
			title: '保质期',
			dataIndex: 'productionExp',
			checked: false
		},
		{
			title: '主供应商',
			dataIndex: 'productionSupplierMainName'
		},
		{
			title: '商品标签',
			dataIndex: 'productionTag',
			checked: false
		},
		{
			title: '状态',
			dataIndex: 'productionStatus'
		},
		{
			title: '一品多码',
			dataIndex: 'productionHasextbarcode',
			checked: false
		},
	]
	// 操作栏通过权限判断是否显示
	if (hasPerm(['supplierBaseProductionsEdit', 'supplierBaseProductionsDelete'])) {
		columns.push({
			title: '操作',
			dataIndex: 'action',
			align: 'center',
			width: 150
		})
	}
	const selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		// columns数字类型字段加入 needTotal: true 可以勾选自动算账
		alert: {
			show: true,
			clear: () => {
				selectedRowKeys.value = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	const loadData = (parameter) => {
		loadTreeData()
		const searchFormParam = cloneDeep(searchFormState.value)
		return supplierProductionsApi.supplierProductionsPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		tableRef.value.refresh(true)
	}
	// 删除
	const deleteSupplierProductions = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		supplierProductionsApi.supplierProductionsDelete(params).then(() => {
			tableRef.value.refresh(true)
		})
	}
	// 批量删除
	const deleteBatchSupplierProductions = (params) => {
		supplierProductionsApi.supplierProductionsDelete(params).then(() => {
			tableRef.value.clearRefreshSelected()
		})
	}
    const xnproductionBrandPageSelectRef = ref();
    const productionBrandSelector = (param) => {
        return supplierBrandsApi.supplierBrandsPage(param).then((data) => {
            if (data.records){
                data.records = data.records.map((item) => {
                    return {
                        name: item.brandName,
                        id: item.id,
                    };
                });
            }
            return Promise.resolve(data)
        })
    }
    nextTick(() => {
        xnproductionBrandPageSelectRef.value.onPage({current: 1});
    });
    const xnproductionSupplierMainPageSelectRef = ref();
    const productionSupplierMainSelector = (param) => {
        return supplierObjectsApi.supplierObjectsPage(Object.assign(param, {objectType:"0"})).then((data) => {
            if (data.records){
                data.records = data.records.map((item) => {
                    return {
                        name: item.objectName,
                        id: item.id,
                    };
                });
            }
            return Promise.resolve(data)
        })
    }
    nextTick(() => {
        xnproductionSupplierMainPageSelectRef.value.onPage({current: 1});
    });
    const xnproductionSupplierListPageSelectRef = ref();
    const productionSupplierListSelector = (param) => {
		return supplierObjectsApi.supplierObjectsPage(Object.assign(param, {objectType:"0"})).then((data) => {
			if (data.records){
				data.records = data.records.map((item) => {
					return {
						name: item.objectName,
						id: item.id,
					};
				});
			}
			return Promise.resolve(data)
		})
    }
    nextTick(() => {
        xnproductionSupplierListPageSelectRef.value.onPage({current: 1});
    });
	const productionStatusOptions = tool.dictList('COMMON_STATUS')
</script>
